package springcloud.service.impl;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;
import springcloud.service.PaymentService;

import java.util.UUID;
import java.util.concurrent.TimeUnit;
@Slf4j
@Service
public class PaymentServiceImpl implements PaymentService {
//==================================服务降级=========================================
    @Override
    public String paymentInfo(Integer id) {
        //正常访问
        return "线程池: " + Thread.currentThread().getName() + " paymentInfo  id:" + id;
    }

    @HystrixCommand(fallbackMethod = "paymentInfoTimeoutHandle",commandProperties = {
            //设置自身调用超过时间的峰值 峰值内可以正常运行
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "5000")
    })
    @Override
    public String paymentInfoTimeout(Integer id) {
        //超时测试
        int timeNum = 2;
        try {
            TimeUnit.SECONDS.sleep(timeNum);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程池: " + Thread.currentThread().getName() + " paymentInfoTimeout  id:" + id;
    }
    public String paymentInfoTimeoutHandle(Integer id) {
        return "8084 访问超时";
    }
//==================================服务熔断=========================================
    @HystrixCommand(fallbackMethod = "paymentCircuitBreakerFallback",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),  // 开启熔断器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),  // 当请求达到这个数量之后，才进行错误占比的计算。
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),  // 半打开休眠时间，熔断之后过了这段休眠时间，就会半打开，尝试接口是否恢复，如果恢复就完全打开熔断器。
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60")  // 错误占比，当错误次数超过这个百分比，就会熔断。
    })
    public String paymentCircuitBreaker(@PathVariable("id") Integer id){
        if(id < 0){
            throw new RuntimeException("ID不能为负数: " + id);
        }

        String serialNumber = IdUtil.simpleUUID();//生成不带-的字符串
        //UUID.randomUUID().toString() == IdUtil.randomUUID() //生成带-的字符串
        return Thread.currentThread().getName() + "  流水号:" + serialNumber + "   " + id;
    }
    public String paymentCircuitBreakerFallback(@PathVariable("id") Integer id){

        return "请稍后再试" ;
    }
}
